package com.farm.sfile.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.farm.parameter.FarmParameterService;

import net.coobird.thumbnailator.Thumbnails;

public class ImgThumbnails {

	/**
	 * 允许的最大压缩图片大小
	 */
	public enum IMG_TYPE {
		MAX("max", "max", 1200), MED("med", "med", 960), MIN("min", "min", 330), NONE("none", "none", 0);
		/**
		 * url标记
		 */
		private String urlIndex;
		/**
		 * 文件标记
		 */
		private String fileIndex;
		private int num;

		public String getUrlIndex() {
			return urlIndex;
		}

		public String getFileIndex() {
			return fileIndex;
		}

		public int getNum() {
			return num;
		}

		/**
		 * @param value
		 * @param num
		 */
		IMG_TYPE(String urlIndex, String fileIndex, int num) {
			this.urlIndex = urlIndex;
			this.num = num;
			this.fileIndex = fileIndex;
		}

		/**
		 * 获得枚举类型，根据url的标记
		 * 
		 * @param type
		 * @return
		 */
		public static IMG_TYPE getEnum(String type) {
			for (IMG_TYPE typenode : values()) {
				if (typenode.getUrlIndex().toUpperCase().equals(type.toUpperCase())) {
					return typenode;
				}
			}
			return null;
		}
	}

	public static File loadThumbnail(String exName, IMG_TYPE img_type, File file) throws IOException {
		// 生成缩略图
		// 文件后缀名
		if (exName == null || exName.trim().isEmpty()) {
			throw new RuntimeException();
		}
		File newfile = getFormatImg(file, img_type, exName);
		// 判断图片是否已经存在了
		if (!newfile.exists()) {
			if (file.getPath().indexOf("." + img_type.getFileIndex() + "." + exName) > 0) {
				throw new RuntimeException("原图片已经为缩略图，此文件可能会引起缩略图重复生成异常请检查程序代码，或所执行操作！");
			}
			float quality = 1f;
			// 不存在则直接变换
			BufferedImage bufferedImage = ImageIO.read(file);
			if (bufferedImage == null) {
				throw new IOException("the file is not exist:");
			}
			int width = bufferedImage.getWidth();
			int toWidth = img_type.getNum();
			if (width < toWidth) {
				toWidth = width;
			}
			Thumbnails.of(file).width(toWidth).toFile(newfile);
			float maxImgsize = FarmParameterService.getInstance()
					.getParameterFloat("config.doc.img.compress.length.max") * 1024;
			if (newfile.length() > maxImgsize) {
				quality = 1f * maxImgsize / newfile.length();
				Thumbnails.of(file).scale(quality).toFile(newfile);
			}
		}
		return newfile;
	}

	/**
	 * 获得图片的特定类型文件
	 * 
	 * @param file
	 *            图片文件
	 * @param type
	 *            图片类型
	 * @return
	 */
	private static File getFormatImg(File file, IMG_TYPE type, String prefix) {
		String plusName = "." + type.getFileIndex() + "." + prefix;
		return new File(file.getPath() + plusName);
	}

}
